package com.edu.whty.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.edu.whty.dao.SchoolResourceDao;
import com.edu.whty.dao.SpecialRepoDao;
import com.edu.whty.dao.SpecialResourceCatalogDao;
import com.edu.whty.dao.SpecialResourcesBaseDao;
import com.edu.whty.entity.base.SpecialRepo;
import com.edu.whty.entity.school.*;
import com.edu.whty.service.SpecialRepoService;
import net.sf.json.JSONArray;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @author luyao
 * @explain
 * @date 2021/5/30
 */
@Component("SpecialRepoService")
public class SpecialRepoServiceImpl implements SpecialRepoService{

    private  static Logger LOGGER = LoggerFactory.getLogger(SpecialRepoServiceImpl.class);

    @Autowired
    private SpecialRepoDao specialRepoDao;

    @Autowired
    private SchoolResourceDao schoolResourceDao;

    @Autowired
    private SpecialResourcesBaseDao specialResourcesBaseDao;

    @Autowired
    private SpecialResourceCatalogDao specialResourceCatalogDao;


    @Override
    public int addSpecialRepo(SpecialRepo specialRepo) {
        return specialRepoDao.addSpecialRepor(specialRepo);
    }

    @Override
    public int updateSpecialRepo(SpecialRepo specialRepo) {
        return specialRepoDao.updateSpecialRepo(specialRepo);
    }

    @Override
    public SpecialRepo getSpecialRepo(String id) {
        return specialRepoDao.selectSpecialRepo(id);
    }

    @Override
    public List<SpecialRepo> getSpecialRepoList(String id) {
        return specialRepoDao.selectSpecialRepoList(id);
    }

    @Override
    public int batchAddSpecialRepo(List<SpecialRepo> list) {
        return specialRepoDao.batchAddSpecialRepo(list);
    }

    @Override
    public void batchUploadSpecialRepo(List<SpecialRepo> list) {
        specialRepoDao.batchUpdateSpecialRepo(list);
    }

    @Override
    public JSONArray queryCatalogTreeByUser(Map<String, Object> mapParam, TextbookQryDto dto) {
        LOGGER.info("queryCatalogTree.param = {}", JSON.toJSONString(mapParam));
        String userId = dto.getUserId();
        String orgId = (String) mapParam.get("orgId");
        String specialResourcesId = null;
        if(mapParam.get("specialResourcesId") != null){
            specialResourcesId = (String) mapParam.get("specialResourcesId");
        }

        String _catalogId = null; //新增条件
        if(mapParam.get("_catalogId") != null){
            _catalogId = (String) mapParam.get("_catalogId");
        }

        Map<String, String> catalogPrivMap = null;
        JSONArray jsonArrayData = new JSONArray();
        /*if (dto.isSupSchoolManager() || "1".equals(dto.getOrgType())
                || "10".equals(dto.getOrgType())) {
            LOGGER.info("超管或者机构或者平台");
        } else {
            //查询当前用户的 专题目录非审核权限
            VisualRangePrivDto specialCataloguePriv = new VisualRangePrivDto();
            specialCataloguePriv.setUserId(userId);
            specialCataloguePriv.setOrgId(orgId);
            specialCataloguePriv.setStatus("0");
            specialCataloguePriv.setPrivType("2"); //专题资源
            specialCataloguePriv.setSpecialResourcesId(specialResourcesId);
            //有权限的专题
            List<SpecialResourcesBaseDto> baselist = schoolResourceDao.queryCataBasePrivWithoutAudit(specialCataloguePriv);
            //
            if(org.springframework.util.CollectionUtils.isEmpty(baselist)){
                return jsonArrayData; //无专题权限
            }
            List<String> specialResourcesIdList = baselist.stream().map(bastDto->bastDto.getId()).collect(Collectors.toList());
            specialCataloguePriv.setSpecialResourcesIdList(specialResourcesIdList);
            List<SpecialResourceCatalogDto> list = schoolResourceDao.queryCataloguePrivWithoutAudit(specialCataloguePriv);
            List<SpecialResourceCatalogDto> listSbase = new ArrayList<>();
            if (!org.springframework.util.CollectionUtils.isEmpty(baselist)) {
                catalogPrivMap = new HashMap<>();
                for (SpecialResourcesBaseDto baseDto : baselist) {
                    SpecialResourceCatalogDto base = new SpecialResourceCatalogDto();
                    base.setCatalogId(baseDto.getId());
                    base.setCatalogName(baseDto.getTopicResourceName());
                    base.settSpecialResourcesId(baseDto.getId());
                    base.setCatalogType("1");//专题
                    listSbase.add(base);
                }
            }
            listSbase.addAll(list);
            for (SpecialResourceCatalogDto catalogDto : listSbase) {
                catalogPrivMap.put(catalogDto.getCatalogId(), catalogDto.gettSpecialResourcesId());
            }

            if (org.springframework.util.CollectionUtils.isEmpty(catalogPrivMap)) {
                return jsonArrayData;
            }
        }*/
        //--------------TODO:---catalogPrivMap-------------------------------------
        List<SpecialResourcesBase> list = schoolResourceDao.selectSelfAndSubscribedRepo(mapParam);
        for (SpecialResourcesBase repo : list) {
            JSONObject rootNode = new JSONObject();
            if (0 == repo.getIsCatalog()) {
                String repoId = repo.getId();
                LOGGER.info("-----repoId=====" + repoId);
                rootNode.put("id", repoId);
                rootNode.put("repoId", repoId);
                rootNode.put("pId", "0");
                rootNode.put("parentId", "ZT");
                rootNode.put("name", repo.getTopicResourceName());
                rootNode.put("isCatalog", 0);
                if (catalogPrivMap == null || (catalogPrivMap.values().contains(repo.getId()))) {
                    jsonArrayData.add(rootNode);
                }
                getCatalogList(jsonArrayData, repo, catalogPrivMap,_catalogId);
            } else {
                if(StringUtils.isNotBlank(dto.getNoBm()) && "3".equals(dto.getNoBm())){//编目专题的注入逻辑  屏蔽带编目
                    rootNode.put("id", repo.getId());
                    rootNode.put("pId", "0");
                    rootNode.put("parentId", "BM");
                    rootNode.put("name", repo.getTopicResourceName());
                    rootNode.put("isCatalog", 1);
                    jsonArrayData.add(rootNode);
                }

            }
        }
        mapParam.put("listCount",list.size());
        return jsonArrayData;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editUserCatalog(List<SpecialResourcesBase> specialResourcesBases) {
        specialRepoDao.deleteUserSpecialRepo(specialResourcesBases);
        schoolResourceDao.editSpecialResource(specialResourcesBases);
    }

    @Override
    public void batchDeleteSpecialRepos(List<SpecialRepo> list) {
        specialRepoDao.deleteSpecialRepo(list);
    }

    @Override
    public SpecialResourcesBase getSpecialRepoBase(String id) {
        return specialResourcesBaseDao.selectById(id);
    }

    @Override
    public void batchAddSpecialRepoBase(List<SpecialResourcesBase> listAdd) {
        specialResourcesBaseDao.batchAddSpecialRepoBase(listAdd);
    }

    @Override
    public void batchUploadSpecialRepoBase(List<SpecialResourcesBase> listUpdate) {
        specialResourcesBaseDao.batchUploadSpecialRepoBase(listUpdate);
    }

    @Override
    public SpecialResourceCatalog getSpecialResCata(String catalogId) {
        return specialResourceCatalogDao.selectById(catalogId);
    }

    @Override
    public void batchAddSpecialResCata(List<SpecialResourceCatalog> list1Add) {
        specialResourceCatalogDao.batchAddSpecialResCata(list1Add);
    }

    @Override
    public void batchUploadSpecialResCata(List<SpecialResourceCatalog> list1Update) {
        specialResourceCatalogDao.batchUploadSpecialResCata(list1Update);
    }

    private void getCatalogList(JSONArray jsonArray, SpecialResourcesBase repo, Map<String, String> catalogPrivMap, String paramCatalogId) {
        //2.获取该专题的目录列表
        SpecialResourceCatalogDto param = new SpecialResourceCatalogDto();
        param.settSpecialResourcesId(repo.getId());
        param.setStatus(0);
        param.setIsShow("1");//展示的
        List<SpecialResourceCatalogDto> catalogList = schoolResourceDao.selectListByModel(param);
        if(StringUtils.isNotBlank(paramCatalogId)){
            getInitNodeInfoData(jsonArray, paramCatalogId, catalogList, repo, catalogPrivMap);
        }else{
            getInitNodeInfoData(jsonArray, "0", catalogList, repo, catalogPrivMap);
        }
    }


    private void getInitNodeInfoData(JSONArray jsonArray, String parentId, List<SpecialResourceCatalogDto> catalogList, SpecialResourcesBase repo, Map<String, String> catalogPrivMap) {
        if (catalogList != null && catalogList.size() > 0) {
            for (int i = 0; i < catalogList.size(); i++) {
                SpecialResourceCatalogDto catalog = catalogList.get(i);
                if (parentId.equals(catalog.getParentId())) {
                    JSONObject jsonData = new JSONObject();
                    jsonData.put("id", catalog.getCatalogId());
                    if ("0".equals(catalog.getParentId())) {
                        jsonData.put("pId", repo.getId());
                        jsonData.put("parentId", repo.getId());
                    } else {
                        jsonData.put("pId", catalog.getParentId());
                        jsonData.put("parentId", catalog.getParentId());
                    }
                    jsonData.put("repoId", repo.getId());
                    jsonData.put("name", catalog.getCatalogName());
                    if (catalogPrivMap == null || (catalogPrivMap.keySet().contains(catalog.getCatalogId()))) {
                        jsonArray.add(jsonData);
                    }
                    getInitNodeInfoData(jsonArray, catalog.getCatalogId(), catalogList, repo, catalogPrivMap);
                }
            }
        }
    }

}
